package cxm.lib.alg;

public class RingBuffer {
	private byte []ring = null;
	private int start = 0;
	private int stop = 0;
	private int count = 0;

	public RingBuffer() {
		this.ring = new byte[512 * 1024]; // 1mb buffer
	}
	public RingBuffer(int length) {
		this.ring = new byte[length];
	}
	
	public int getCount() {
		return this.count;
	}
	
	// pub buffer into ring
	// return put length
	public synchronized int putBuffer(byte []buffer) {
		int empty = this.ring.length - this.count;
		int copyCount = empty > buffer.length ? buffer.length : empty;
		for (int i = 0; i < copyCount; i++) {
			this.ring[this.stop] = buffer[i];
			this.stop = (this.stop + 1) % this.ring.length;
			this.count++;
		}
		return copyCount;
	}
	
	// pop buffer from ring
	// return get length
	public synchronized int getBuffer(byte []buffer) {
		int copyCount = this.count > buffer.length ? buffer.length : this.count;
		for (int i = 0; i < copyCount; i++) {
			buffer[i] = this.ring[this.start];
			this.start = (this.start + 1) % ring.length;
			this.count--;
	 	}
		return copyCount;
	}
	
	// has data least
	public boolean hasData(int len) {
		return this.count > len;
	}
}
